<?php

function controller_home($config) {
    if (isset($_SESSION['logged'])){
		if ((isset($config['ruri'][0])) && ($config['ruri'][0] == 'logout')){
			unset($_SESSION['logged']);
			header('Location: '.$config['home_url']);
		}else
			header('Location: '.$config['home_url']."agenda");
	}else if (isset($_POST['loggin'])){
		$username = strtolower($_POST['uname']);
		$password = md5(strtolower($_POST['pass']));
		if (check_login($config,$username,$password)) {
			$redir = $config['home_url']."agenda";
		} else {
			$_SESSION['logfail'] = "FAIL";
			$redir = $config['home_url'];
		}
		header('Location: '.$redir);
	} else
		view_login($config,array());
}

function check_login($config,$username,$md5) {
	$db =  new db($config);
	$retval = false;
	$result = $db->query("SELECT * FROM mn_crew WHERE username = '".urlencode($username)."' AND password = '$md5'");
	if ($result && $db->rowCount() > 0) {
		$retval = true;
		$_SESSION['logged']['id'] = $result[0]['idCrew'];
		$_SESSION['logged']['uname'] = $result[0]['username'];
		$_SESSION['logged']['role'] = $result[0]['role'];
		$_SESSION['logged']['no_hape'] = $result[0]['no_hape'];
		$_SESSION['logged']['email'] = $result[0]['email'];
		$_SESSION['logged']['twitter'] = $result[0]['twitter'];
	}
	//var_dump($result);
	return $retval;
}
